package logic

import (
	"context"
	"errors"
	"login-guard/loginrpc/internal/svc"
	"login-guard/loginrpc/loginrpc"
	"login-guard/models/cache"
	"login-guard/models/mysql"
	"login-guard/pkg"

	"github.com/zeromicro/go-zero/core/logx"
)

type LoginLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewLoginLogic(ctx context.Context, svcCtx *svc.ServiceContext) *LoginLogic {
	return &LoginLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *LoginLogic) Login(in *loginrpc.LoginRequest) (*loginrpc.LoginResponse, error) {
	// todo: add your logic here and delete this line
	var Login mysql.Login
	mysql.DB.Debug().Where("account = ?", in.Account).Find(&Login)
	if Login.ID == 0 {
		if Login.ID != 0 {
			return nil, errors.New("用户存在")
		}
		mysql.DB.Debug().Create(&Login)
	}
	if Login.Password != pkg.MD5(in.Password) {
		return nil, errors.New("密码错误")
	}
	result, _ := cache.RDB.Get(l.ctx, "captchaCode"+in.Account).Result()
	if result == "" {
		return nil, errors.New("图形验证码错误")
	}
	return &loginrpc.LoginResponse{
		LoginId: int64(Login.ID),
	}, nil
}
